import { onShareAppMessage } from '@dcloudio/uni-app'
import { useI18n } from 'vue-i18n'
import { getNavigateUrl, makeCanvas } from '@/utils/mpHelper'
import { useApplianceStore } from '@/store/appliance'
import { useAuthStore } from '@/store/auth'
import { useAccountStore } from '@/store/account'
import netconfig from '@/config/netconfig'
import aesHelper from '@/utils/aesHelper'
import { useEnvStore } from '@/store/env'

export function useHeaderBarShare(options?: {
  vib: Ref<string> | ComputedRef<string>
  name: Ref<string> | ComputedRef<string>
  type: Ref<string> | ComputedRef<string>
}) {
  const component = getCurrentInstance() as WechatMiniprogram.Component.Instance<any, any, any>
  const i18n = useI18n()
  const applianceStore = useApplianceStore()
  const authStore = useAuthStore()
  const accountStore = useAccountStore()

  onShareAppMessage(async () => {
    const vib = options?.vib.value || applianceStore.current?.vib
    const name = options?.name.value || applianceStore.current?.name
    const type = options?.type.value || applianceStore.current?.type
    const userId = aesHelper.decrypt(authStore.ciamId, authStore.key, authStore.iv)
    const shareName = accountStore.ownerName || userId
    const shareTitle = i18n.t('GotoShare.ShareWithYouBefore.Text') + name + i18n.t('GotoShare.ShareWithYouAfter.Text')
    const sharePath = getNavigateUrl('/pages/navigator/index/index', {
      cur: 0,
      sharingtoken: accountStore.sharetoken,
      name: shareName,
      userId,
      recommend: true,
      type,
    })
    let imageUrl = ''
    try {
      imageUrl = await makeCanvas(`${netconfig.PHOTO_IMAGE}${vib}/${vib}.png`, component)
      console.log('imageUrl', imageUrl)
    } catch (e) {
      console.error('获取分享图片失败', e)
    }
    const shareMessage = {
      title: shareTitle,
      imageUrl,
      path: sharePath,
    }
    return shareMessage
  })
}
